from pymongo import MongoClient
import pymongo
import os
from google.cloud import speech

client = speech.SpeechClient.from_service_account_json('D:\\StoT-7214e76c5aa3.json')

config = speech.RecognitionConfig(
    encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
    audio_channel_count=2,
    language_code="en-US",
)
client = MongoClient(port=27017)
db=client['tiktok']
for col in db.list_collection_names():
    for obj in db[col].find():
        if len(obj['video_feature']['audio']['yamnet'])!=0:
            id=obj['_id']
            with open('D:\\Work\\kusuri\\wav_pi\\' + id + '.wav', "rb") as audio_file:
                content = audio_file.read()
            audio = speech.RecognitionAudio(content=content)
            operation = client.long_running_recognize(config=config, audio=audio)
            response = operation.result(timeout=90)
            converted_text=''
            for result in response.results:
                # The first alternative is the most likely one for this portion.
                converted_text+=result.alternatives[0].transcript+' '
            db[col].update_one({'_id': id}, {'$set': {'text_feature.converted_text': converted_text}})
            print(db[col].find_one({'_id': id}))
